package com.authsphere.security.social.common;

import me.zhyd.oauth.cache.AuthStateCache;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @program: AuthSphere
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/22 10:36
 **/
public class ThirdPartyAuthStateCache implements AuthStateCache {
    private final RedisTemplate<String, String> redisTemplate;

    private final static String DEFAULT_PREFIX = "authsphere:thirdparty:state:";

    private String prefix = DEFAULT_PREFIX;

    public ThirdPartyAuthStateCache(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void cache(String key, String value) {
        redisTemplate.opsForValue().set(buildKey(key), value);
    }

    @Override
    public void cache(String key, String value, long timeout) {
        redisTemplate.opsForValue().set(buildKey(key), value, timeout, TimeUnit.SECONDS);
    }

    @Override
    public String get(String key) {
        return redisTemplate.opsForValue().get(buildKey(key));
    }

    @Override
    public boolean containsKey(String key) {
        return Optional.ofNullable(redisTemplate.hasKey(buildKey(key))).orElse(false);
    }

    public String buildKey(String key) {
        return prefix + key;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }
}
